use std::time::Duration;
use cpal::{BufferSize, SampleFormat, SampleRate, StreamConfig};
use cpal::traits::DeviceTrait;
use tokio::time::sleep;

pub(crate) mod lcpal;
pub(crate) mod lmp3;
pub(crate) mod lsymphonia;
/* 播放 mp3 的声音 */
pub(crate) async fn play_mp3_sound(path: &'static str) -> Result<(), anyhow::Error> {
    let (defalut_output, config) = lcpal::init_defalut_output()?;
    let (tx, rx) = tokio::sync::mpsc::channel::<Vec<f32>>(10);
    let config2 = config.clone();
    tokio::spawn(async move {
        lmp3::play_mp3(path, &config, tx).await.unwrap();
    });
    lcpal::play_stream(defalut_output, &config2, rx, 10000).await?;

    Ok(())
}

pub(crate) async fn play_sound(path: &'static str) -> Result<(), anyhow::Error> {
    let (defalut_output, mut config) = lcpal::init_defalut_output()?;
   
    let (tx, mut rx) = tokio::sync::mpsc::channel::<Vec<f32>>(10);
    tokio::spawn(async move {
        lsymphonia::read_sound_file(path, config.sample_rate.0, tx).await.unwrap();
    });
    sleep(Duration::from_millis(100)).await;
    let (time_t, sample_rate, channels) = if let Ok(d) = rx.try_recv() {
        if !d.is_empty() {
            let t = d[0];
            let mut channels = 0;
            let r = if d.len() == 3 {
                channels = d[2] as u16;
                d[1] as u32
            }else { 0 };
            (t as u64, r, channels)
        }else { (0,0 ,0) }
    }else { (0,0,0) };
    lcpal::play_stream(defalut_output, &config, rx, time_t).await?;

    Ok(())
}

fn if_device(){
    // // 创建自定义配置
    // let config = StreamConfig {
    //     channels: 1,                // 立体声（2 声道）
    //     sample_rate: cpal::SampleRate(44100), // 采样率 44100 Hz
    //     buffer_size: cpal::BufferSize::Default, // 使用默认缓冲区大小
    // };
    //
    // // 检查设备是否支持该配置（可选但推荐）
    // if let Ok(mut supported_configs) = defalut_output.supported_output_configs() {
    //     let is_supported = supported_configs
    //         .any(|cfg| cfg.sample_format() == SampleFormat::F32
    //             && cfg.max_sample_rate() >= config.sample_rate
    //             && cfg.channels() >= config.channels);
    //
    //     if !is_supported {
    //         println!("设备不支持该配置");
    //         return Err(anyhow::anyhow!("设备不支持该配置"));
    //     }else {
    //         println!("设备支持该配置");
    //     }
    // }
}